/*
 *   Copyright 2023 <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.asialjim.encommunicate.rsa.management.key;

import com.asialjim.encommunicate.base.rsa.key.RSAClientKey;
import com.asialjim.encommunicate.base.rsa.key.RSAKeys;
import com.asialjim.encommunicate.base.rsa.key.RSAServerKey;
import com.asialjim.encommunicate.rsa.management.pojo.AppEnDecryptInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 基于内存的 RSA 密钥对 事件监听器
 *
 * @author Copyright © <a href="mailto:asialjim@hotmail.com">Asial Jim</a>   Co., LTD
 * @version 1.0
 * @since 2023/2/27, &nbsp;&nbsp; <em>version:1.0</em>, &nbsp;&nbsp; <em>java version:17</em>
 */
@Component
public class RSAKeysEventListener implements ApplicationListener<RSAKeysEvent> {
    @Autowired private List<RSAKeyRepository> repositories;

    @Override
    public void onApplicationEvent(RSAKeysEvent event) {
        RSAKeys keys = event.keys();
        String appid = keys.getAppid();
        RSAClientKey clientKey = keys.getClientKey();
        RSAServerKey serverKey = keys.getServerKey();

        AppEnDecryptInfo info = new AppEnDecryptInfo();
        info.setAppid(appid);
        info.setName(keys.getName());
        info.setClientPriKey(clientKey.getPriKey());
        info.setClientPubKey(clientKey.getPubKey());
        info.setServerPriKey(serverKey.getPriKey());
        info.setServerPubKey(serverKey.getPubKey());
        info.setReqEncEnable(true);
        info.setResEncEnable(true);

        repositories.parallelStream().forEach(repository ->{
            try {
                repository.modify(info);
            } catch (Throwable t){
                // do nothing here, or log
            }
        });
    }
}